package com.fastjars.business.shiro.filter;

import com.fastjars.business.spring.http.Resp;
import org.apache.commons.util.RequestUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * PermissionFilter
 * 检查是否有权限 URL
 * @author Brant Liu <br>
 * 邮箱：lbf1988@qq.com <br>
 * 日期：2018/5/9
 * @version 1.0.0
 */
public class PermissionFilter extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        if(null != mappedValue){
            String[] array = (String[])mappedValue;
            for (String permission : array) {
                if(subject.isPermitted(permission)){
                    return true;
                }
            }
        }
        HttpServletRequest httpRequest = ((HttpServletRequest)request);
        String uri = httpRequest.getRequestURI();//获取URI
        String basePath = httpRequest.getContextPath();//获取basePath
        if(null != uri && uri.startsWith(basePath)){
            uri = uri.replace(basePath, "");
        }
        if(subject.isPermitted(uri)){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        Subject subject = this.getSubject(servletRequest, servletResponse);
        if (subject.getPrincipal() == null) {
            this.saveRequestAndRedirectToLogin(servletRequest, servletResponse);
            return false;
        }
        super.saveRequest(servletRequest);
        if (RequestUtils.isAjaxRequest((HttpServletRequest) servletRequest)) {
            WriterUtils.write(servletResponse, Resp.unauthorized().build().toJsonString());
            return false;
        }
        WebUtils.issueRedirect(servletRequest, servletResponse, super.getUnauthorizedUrl());
        return false;
    }
}
